#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
认证服务层
处理用户认证相关的业务逻辑
"""

from typing import Dict, Optional, Any
from datetime import datetime
from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
from config import current_config
from models import User
import hashlib


class AuthService:
    """认证服务类"""
    
    def __init__(self, db_session: Session):
        self.db_session = db_session
    
    def authenticate_user(self, username: str, password: str) -> Dict[str, Any]:
        """
        用户认证
        
        Args:
            username: 用户名
            password: 密码
            
        Returns:
            认证结果字典
        """
        try:
            # 灰度模式优先验证
            if current_config.GRAY_MODE:
                gray_result = self._authenticate_gray_mode(username, password)
                if gray_result['success']:
                    return gray_result
            
            # 普通数据库验证
            return self._authenticate_database(username, password)
            
        except Exception as e:
            return {
                'success': False,
                'message': f'Authentication error: {str(e)}',
                'user': None
            }
    
    def _authenticate_gray_mode(self, username: str, password: str) -> Dict[str, Any]:
        """灰度模式认证"""
        if username == current_config.GRAY_USERNAME and password == current_config.GRAY_PASSWORD:
            return {
                'success': True,
                'message': 'Login successful (Gray Mode)',
                'user': {
                    'id': 'gray_admin',
                    'username': username,
                    'email': 'admin@gray-mode.com',
                    'role': 'administrator',
                    'mode': 'gray',
                    'permissions': ['read', 'write', 'admin']
                }
            }
        return {'success': False, 'message': 'Gray mode authentication failed', 'user': None}
    
    def _authenticate_database(self, username: str, password: str) -> Dict[str, Any]:
        """数据库认证"""
        try:
            user = self.db_session.query(User).filter(
                User.username == username,
                User.password == password,  # 生产环境应使用加密密码
                User.is_active == True
            ).first()
            
            if user:
                return {
                    'success': True,
                    'message': 'Login successful',
                    'user': {
                        'id': str(user.id),
                        'username': user.username,
                        'email': user.email or '',
                        'role': user.role,
                        'mode': 'normal',
                        'permissions': user.permissions or ['read']
                    }
                }
            
            return {
                'success': False,
                'message': 'Invalid credentials',
                'user': None
            }
            
        except SQLAlchemyError as e:
            return {
                'success': False,
                'message': f'Database error: {str(e)}',
                'user': None
            }
    
    def register_user(self, user_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        用户注册
        
        Args:
            user_data: 用户数据
            
        Returns:
            注册结果
        """
        try:
            # 检查用户名是否已存在
            existing_user = self.db_session.query(User).filter(
                User.username == user_data.get('username')
            ).first()
            
            if existing_user:
                return {
                    'success': False,
                    'message': 'Username already exists',
                    'user_id': None
                }
            
            # 创建新用户
            new_user = User(
                username=user_data.get('username'),
                password=user_data.get('password'),  # 生产环境应加密
                email=user_data.get('email', ''),
                role=user_data.get('role', 'user'),
                permissions=user_data.get('permissions', ['read']),
                is_active=True
            )
            
            self.db_session.add(new_user)
            self.db_session.commit()
            
            return {
                'success': True,
                'message': 'User registered successfully',
                'user_id': str(new_user.id)
            }
            
        except SQLAlchemyError as e:
            self.db_session.rollback()
            return {
                'success': False,
                'message': f'Registration error: {str(e)}',
                'user_id': None
            }
    
    def get_user_by_id(self, user_id: str) -> Dict[str, Any]:
        """根据ID获取用户信息"""
        try:
            user = self.db_session.query(User).filter(
                User.id == int(user_id)
            ).first()
            
            if user:
                return {
                    'success': True,
                    'user': user.to_dict()
                }
            
            return {
                'success': False,
                'message': 'User not found',
                'user': None
            }
            
        except (ValueError, SQLAlchemyError) as e:
            return {
                'success': False,
                'message': f'Error fetching user: {str(e)}',
                'user': None
            }
    
    def get_all_users(self) -> Dict[str, Any]:
        """获取所有用户"""
        try:
            users = self.db_session.query(User).all()
            users_data = [user.to_dict() for user in users]
            
            return {
                'success': True,
                'users': users_data,
                'count': len(users_data)
            }
        except SQLAlchemyError as e:
            return {
                'success': False,
                'message': f'Error fetching users: {str(e)}',
                'users': [],
                'count': 0
            }